import adminListView from '$v/adminList';
import {
    addAdminRequest,
    adminListRequest,
    deleteAdminRequest,
    isLoginRequest
} from "$a/admin"

async function showAdminList(res) {
    let adminListResult = null
    try {
        adminListResult = await adminListRequest();
        // console.log(adminListResult);
    } catch (e) {
        alert("获取管理员列表异常:" + e.message)
        if (!e.isLogin) {
            return router.go("/login");
        }
    }
    res.render(adminListView({
        adminList: adminListResult
    }))
}
export default async (req, res) => {
    //路由切换的时候验证登录
    try {
        await isLoginRequest();
    } catch (e) {
        //请求异常后提示用户
        alert("有异常" + e.message)
        //判断是否是权限异常
        if (!e.isLogin) {
            return router.go("/login");
        }
    }
    await showAdminList(res)
    const oSaveAdmin = document.getElementById("saveAdminBtn");
    document.onclick = async function (e) {
        if (e.target.id === 'saveAdminBtn') {
            //获取用户输入的信息
            const adminNameValue = document.adminForm.adminName.value.trim();
            const passwordValue = document.adminForm.password.value.trim();
            const rePasswordValue = document.adminForm.rePassword.value.trim();

            //判断是否为空
            if (!adminNameValue || !passwordValue || !rePasswordValue) {
                return alert("账号密码不能为空!!!!")
            }
            //判断两次密码是否一致
            if (passwordValue !== rePasswordValue) {
                return alert("两次密码输入的不一致")
            }

            //发送ajax请求
            try {
                await addAdminRequest({
                    adminName: adminNameValue,
                    password: passwordValue,
                    regTime: new Date().toLocaleString()
                })
                alert('添加成功')
                document.getElementById('closedd').click()
                document.adminForm.reset()
                showAdminList(res)
            } catch (e) {
                alert(e.message)
                document.adminForm.reset()
                //判断是否是权限异常
                if (!e.isLogin) {
                    document.getElementById('closedd').click()
                    return router.go("/login");
                }
            }
        }
        if (e.target.nodeName === 'BUTTON' && e.target.parentNode.nodeName === 'TD') {
            //获取当前删除按钮对应的adminName(在生成删除按钮的时候 就把自定义属性设置上去)
            const adminName = e.target.dataset.adminname;
            // console.log(adminName);
            //发送删除请求
            try {
                await deleteAdminRequest(adminName);
                alert("删除管理员" + adminName + "成功")

                //删除成功 重新渲染视图
                showAdminList(res);
            } catch (e) {
                alert("删除管理员" + adminName + "异常")
                //判断是否是权限异常
                if (!e.isLogin) {
                    return router.go("/login");
                }
            }
        }
    }
}